require 'digest/md5'

class User < ActiveRecord::Base
  
  @@account_types = ['operator', 'observer']

  has_and_belongs_to_many :grid_events

  validates_presence_of :login, :hashed_password, :account_type
  validates_uniqueness_of :login
  validates_inclusion_of :account_type, :in => @@account_types

  def self.account_types
    @@account_types
  end

  def self.authenticate(login, password)
    user = self.find_by_login(login)
    if user
      expected_password = encrypted_password(password)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end

  def password
    @password
  end

  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    self.hashed_password = User.encrypted_password(self.password)
  end

  def logout
    self.update_attributes!(:is_logged_in => false)
  end

  private

  def self.encrypted_password(password)
    Digest::MD5.hexdigest(password)
  end

end
